package leetcode101.tree;

import java.util.Arrays;

/**
 * @author Synhard
 * @version 1.0
 * @class Code22
 * @description 106. 从中序与后序遍历序列构造二叉树
 * 根据一棵树的中序遍历与后序遍历构造二叉树。
 *
 * 注意:
 * 你可以假设树中没有重复的元素。
 *
 * 例如，给出
 *
 * 中序遍历 inorder = [9,3,15,20,7]
 * 后序遍历 postorder = [9,15,7,20,3]
 * 返回如下的二叉树：
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-06-27 9:01
 */
public class Code22 {
    public static void main(String[] args) {

    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int length = inorder.length;
        if (length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[length - 1]);
        if (length == 1) {
            return root;
        }

        int counter = 0; // 记录根节点在中序遍历中的位置
        for (int j : inorder) {
            if (postorder[length - 1] != j) {
                counter++;
            } else {
                break;
            }
        }
        root.left = buildTree(Arrays.copyOfRange(inorder, 0, counter), Arrays.copyOfRange(postorder, 0, counter));
        root.right = buildTree(Arrays.copyOfRange(inorder, counter + 1, length), Arrays.copyOfRange(postorder, counter, length - 1));
        return root;
    }
}
